package post

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdatePostLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserUpdatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdatePostLogic {
	return &UserUpdatePostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserUpdatePostLogic) UserUpdatePost(req *types.UserPostUpdateReq) (resp *types.Empty, err error) {
	// 参数验证
	if req.Id <= 0 {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.ErrorParam)
	}

	if strings.TrimSpace(req.Title) == "" {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.PostTitleEmpty)
	}

	if strings.TrimSpace(req.Content) == "" {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.PostContentEmpty)
	}

	if req.UserId <= 0 {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.ErrorParam)
	}

	// 查询帖子是否存在
	var post model.CsCommunityPost
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{}).
		Where("id = ?", req.Id).Find(&post).Error; err != nil {
		logx.Errorf("查询帖子失败: %v", err)
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if post.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.PostNotFound)
	}

	// 验证权限：只能修改自己的帖子
	if post.CreateUser != req.UserId {
		return nil, e.NewGrpcErr(codes.PermissionDenied, e.PermissionDenied)
	}

	// 更新帖子内容
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{}).
		Where("id = ?", req.Id).
		Updates(map[string]interface{}{
			"title":   strings.TrimSpace(req.Title),
			"content": strings.TrimSpace(req.Content),
		}).Error; err != nil {
		logx.Errorf("更新帖子失败: %v", err)
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
